package com.zzw.thread.lock;

/**
 * @author zzw
 * @see
 * @since 2018/2/13
 */
public class Synchronization2 {
    private static int resourceCount = 3;
    private static Object box = new Object();

    public static void main(String[] args) {
        Thread producer = new Thread(() -> {
            try {
                while (true) {
                    producer();
                }
            } catch (InterruptedException e) {}
        });
        Thread consumer = new Thread(() -> {
            try {
                while (true) {
                    consumer();
                }
            } catch (InterruptedException e) {}
        });

        producer.start();
        consumer.start();
    }

    public static void producer() throws InterruptedException {
        synchronized (box) {
            resourceCount++;
            box.notifyAll();
            System.out.println("Producer: resourceCount + 1 = " + resourceCount);
        }
        Thread.sleep(1000);
    }

    public static void consumer() throws InterruptedException {
        synchronized (box) {
            while (resourceCount == 0) {
                box.wait();
            }
            resourceCount--;
            System.out.println("Consumer: resourceCount - 1 = " + resourceCount);
        }
        Thread.sleep(500);
    }
}
